﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace CommonNet48.SerializerUtils
{
    /// <summary>
    /// 二进制序列化帮助类。
    /// </summary>
    public class BinaryHelper
    {
        /// <summary>
        /// 将Object类型对象(注：必须是可序列化的对象)转换为二进制序列字符串
        /// </summary>
        /// <param name="obj">被序列化的对象</param>
        /// <returns>字符串</returns>
        public static string SerializeObject<T>(T obj)
        {
            if (obj == null)
                return string.Empty;
            string sRet = string.Empty;
            try
            {
                IFormatter formatter = new BinaryFormatter();
                using (MemoryStream stream = new MemoryStream())
                {
                    formatter.Serialize(stream, obj);
                    byte[] byt = new byte[stream.Length];
                    byt = stream.ToArray();
                    sRet = Convert.ToBase64String(byt);
                }
            }
            catch //(Exception ex)
            {
                sRet = string.Empty;
            }
            return sRet;
        }

        /// <summary>
        /// 将二进制序列字符串转换为Object类型对象
        /// </summary>
        /// <typeparam name="T">反序列化对象类型</typeparam>
        /// <param name="str">反序列化的字符串</param>
        /// <returns>对象实体</returns>
        public static T DeserializeObject<T>(string str)
        {
            if (str.Trim().Length == 0)
                return default(T);
            T objRet = default(T);
            try
            {

                IFormatter formatter = new BinaryFormatter();
                byte[] byt = Convert.FromBase64String(str);
                using (Stream stream = new MemoryStream(byt, 0, byt.Length))
                {
                    objRet = (T)formatter.Deserialize(stream);
                }
            }
            catch //(Exception ex)
            {
                objRet = default(T);
            }
            return objRet;
        }

        /// <summary>
        /// 复制引用类型对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">复制的对象实体</param>
        /// <returns>新的对象实体</returns>
        public static T CopyObject<T>(T obj)
        {
            if (obj == null)
                return default(T);
            T objRet = default(T);
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext());
                    bf.Serialize(ms, obj);
                    ms.Seek(0, SeekOrigin.Begin);
                    objRet = (T)bf.Deserialize(ms);
                }
            }
            catch //(Exception ex)
            {
                objRet = default(T);
            }
            return objRet;
        }

        /// <summary>
        /// 保存对象到文件
        /// </summary>
        /// <param name="sFileFullName">文件完整路径</param>
        public static void SaveObjToFile<T>(string sFileFullName, T obj)
        {
            using (FileStream fs = new FileStream(sFileFullName, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, obj);
                fs.Close();
            }
        }

        /// <summary>
        /// 从文件读取对象
        /// </summary>
        /// <param name="sFileFullName">文件完整路径</param>
        /// <returns>object对象</returns>
        public static T ReadObjFromFile<T>(string sFileFullName)
        {
            if (!File.Exists(sFileFullName))
                return default(T);
            T obj = default(T);
            try
            {
                using (FileStream fs = new FileStream(sFileFullName, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    obj = (T)formatter.Deserialize(fs);
                    fs.Close();
                }
            }
            catch //(Exception ex)
            {
                obj = default(T);
            }
            return obj;
        }
    }
}
